/*****************************************************************************
 *   Copyright 2005 Tim A Wang
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 *
 ****************************************************************************/
package com.jb.web.util;

import com.jb.web.bean.BaseComponent;

import java.util.Enumeration;
import java.util.List;
import java.util.Vector;

import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;


public class JBNode implements TreeNode {
    BaseComponent component;
    JBNode parent;
    Vector children = new Vector();

    public JBNode(BaseComponent component) {
        this.component = component;
    }

    public boolean getAllowsChildren() {
        return true;
    }

    public TreeNode getChildAt(int i) {
        return (children == null) ? null : (TreeNode) children.get(i);
    }

    public int getChildCount() {
        return children.size();
    }

    public BaseComponent getComponent() {
        return component;
    }

    public int getIndex(TreeNode node) {
        return children.indexOf(node);
    }

    public boolean isLeaf() {
        return children.size() == 0;
    }

    public void setParent(JBNode jbNode) {
        parent = jbNode;
    }

    public TreeNode getParent() {
        return parent;
    }

    public void setSize(long newSize) {
        //
    }

    public static TreeModel getTreeModel(BaseComponent baseComponent) {
        JBNode fn = new JBNode(baseComponent);
        fn.populate();

        return new DefaultTreeModel(fn);
    }

    public void addChild(JBNode jbNode) {
        jbNode.setParent(this);
        children.add(jbNode);
    }

    public Enumeration children() {
        return children.elements();
    }

    public void populate() {
        List list = component.getChildren();

        for (int i = 0; i < list.size(); i++) {
            JBNode jbNode = new JBNode((BaseComponent) list.get(i));
            addChild(jbNode);
            jbNode.populate();
        }
    }

    public String toString() {
        return component.toString();
    }
}
